package com.inmarry.action;

import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Date;

import org.apache.struts.action.*;
import org.apache.struts.util.*;
import org.apache.struts.validator.*;

import com.inmarry.model.*;
import com.inmarry.form.*;
import com.inmarry.util.*;

import com.ibatis.sqlmap.client.SqlMapClient;


public final class Login extends Action {
    
    public ActionForward execute(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest req,
            HttpServletResponse res) throws Exception {

         HttpSession session = req.getSession(true);

         if ( (session.getAttribute("user")) != null ) {
            //证明已经登录了
            return mapping.findForward("loginsuccess");
         }

        //建立错误消息文件
        ActionMessages errors = new ActionMessages();

        //得到用户输入的用户名和密码
        String userName = (String)((DynaValidatorForm)form).get("userName");
        //用户输入的密码
        String password = (String)((DynaValidatorForm)form).get("password");
        //用户输入的验证码
        String verifyCodeInForm = (String)((DynaValidatorForm)form).get("verifyCode");
        String verifyCodeInSession = (String)session.getAttribute("verifycode");

        if ( !verifyCodeInForm.equalsIgnoreCase(verifyCodeInSession) ) {
            errors.add("verifyCode", new ActionMessage("login.verifycode.not.currect"));
            saveErrors(req, errors);
            return new ActionForward(mapping.getInput());
        } 
 
        //检查用户是否存在

         //get SQLMap;
        SqlMapClient sqlMap = DBConnection.getSqlMapInstance();
        //检查相应的用户名是否存在
        UserBase user = (UserBase)sqlMap.queryForObject("getUserByName", userName);
        if ( user == null ) {
            errors.add("userName", new ActionMessage("login.username.isnotexists", userName));
            saveErrors(req, errors);
            return new ActionForward(mapping.getInput());
        }

        //检查用户是否已经被激活。
        //如果没有激活，则登录不成功
        if ( !(user.getIsActive()).equalsIgnoreCase("Y") ) {
            errors.add("userName", new ActionMessage("login.user.not.active", userName));
            saveErrors(req, errors);
            return new ActionForward(mapping.getInput());
        }


        //加密用户密码
        String securityPassword = MD5.md5encoder(password);

        if ( (user.getPassword()).equals(securityPassword) ) {
            //注册成功
            session.setAttribute("user", user);
            return mapping.findForward("loginsuccess");
        } else {
            errors.add("password", new ActionMessage("login.not.correct.password"));
            saveErrors(req, errors);
            return new ActionForward(mapping.getInput());
        }

    }

}
